<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/27
 * Time: 1:56 PM
 */
namespace app\common\exceptions;

use app\common\traits\MessageViewTrait;
use app\common\traits\ResponseJsonTrait;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Throwable;

class Handler extends \Illuminate\Foundation\Exceptions\Handler
{
    use ResponseJsonTrait;
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     * @param Exception $exception
     * @throws Exception
     */
    public function report(Throwable $exception)
    {
        if ($this->shouldntReport($exception)) {
            return;
        }
        try {
            // 记录错误日志
            if (!app()->runningInConsole()) {
                \Log::error('http parameters', request()->input());
            }
            \Log::error($exception);
        } catch (Exception $ex) {
            dump($exception);
            dd($ex);
        }


        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     * @throws Exception
     */
    public function render($request, Throwable $exception)
    {
        // 全局异常，json返回
        if ($exception instanceof BizException) {
            if($request->ajax() || $request->expectsJson()){
                return $this->errorJson($exception->getMessage(), $exception->getData());
            } else {
                return response()->view('error', [
                    'redirect' => $exception->getRedirect(),
                    'message' => $exception->getMessage()
                ])->send();
            }
        }
        //后台登录异常--修改密码，单点登录
        if ($exception instanceof AuthenticationException) {
            return redirect()->guest('/admin/login/index');
        }
        return parent::render($request, $exception);
    }
}